package com.example.dmgame.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.example.dmgame.bean.ChapterListItem;

import android.os.AsyncTask;
import android.util.Log;

public class JsonAsyncTask extends AsyncTask<String, Void, List<ChapterListItem>>{

	private Callback mCallback;
	private int mRow;
	public JsonAsyncTask(Callback callback,int row) {
		// TODO Auto-generated constructor stub
		this.mCallback = callback;
		this.mRow =row+5;
	}

	@Override
	protected List<ChapterListItem> doInBackground(String... params) {
		// TODO Auto-generated method stub
		List<ChapterListItem> chapterListItems = new ArrayList<ChapterListItem>();
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet get = new HttpGet(params[0]);
		try{
			HttpResponse response = httpClient.execute(get);
			if(response.getStatusLine().getStatusCode()==200){
				HttpEntity entity = response.getEntity();
				byte[] bytes=EntityUtils.toByteArray(entity);
				String jsonStr = new String(bytes, "utf-8");
				
				JSONObject jsonObject = new JSONObject(jsonStr);
				JSONObject data = jsonObject.getJSONObject("data");
				for(int index=0;index<mRow;index++){
					JSONObject chapter = data.getJSONObject(index+"");
					String id = chapter.getString("id");
					String title = chapter.getString("title");
					String pubdate = chapter.getString("pubdate")+"000";
					String senddate = chapter.getString("senddate")+"000";
					String litpic = chapter.getString("litpic");
					String feedback = chapter.getString("feedback");
					Log.i("JsonAsyncTask", "---->>id="+id+",title="+title);
					ChapterListItem chapterListItem = new ChapterListItem(id, title, pubdate, senddate,litpic,feedback);
					Log.i("JsonAsyncTask", "----->>chapterListItem="+chapterListItem);
					chapterListItems.add(chapterListItem);
					Log.i("JsonAsyncTask", "----->>chapterListItems="+chapterListItems);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return chapterListItems;
	}
	
	@Override
	protected void onPostExecute(List<ChapterListItem> result) {
		// TODO Auto-generated method stub
		Log.i("JsonAsyncTask", "---->>result="+result);
		mCallback.sendData(result, mRow);
	}
	
	public interface Callback{
		public void sendData(List<ChapterListItem>chapterListItems,int row);
	}

}
